data = load('ex1data1.txt'); 				%加载文件数据
plot(data(:,1),data(:,2),'r*','markersize',15); 	%可视化数据集
xlabel('Population of city');
ylabel('Profit of a food truck in the city');
title('Population and Profit Scatter Plot');

iter_times = 1500;					%设置迭代次数
alpha = 0.01;						%设置alpha，学习率
theta = zeros(2,1);					%initial fitting parameter
theta_s = theta;					%设置用于同步更新的变量
x = [ones(length(data(:,1)),1),data(:,1)];		%保存预测值
cost_values = zeros(iter_times,1);			%保存误差	

for iter = 1:iter_times,
	theta_s(1) = theta(1) - alpha/length(data(:,1)) * sum(x * theta - data(:,2));
	theta_s(2) = theta(2) - alpha/length(data(:,1)) * sum((x * theta - data(:,2)).*x(:,2));
	theta = theta_s;				%同步更新theta
	cost_values(iter) = sum((x * theta - data(:,2)).^2)/(2*length(data(:,1)));
end
hold on;
plot(data(:,1), x * theta, 'g','markersize',15);	%画图

theta0_val = linspace(-10,10,100);
theta1_val = linspace(-1,4,100);
cost_val = zeros(length(theta0_val),length(theta1_val));

for_theta0_val = theta0_val;
for_theta1_val = theta1_val;
for_cost_val = cost_val;


for i = 1 : length(theta0_val)
	for j = 1 : length(theta1_val)
		theta_temp = [theta0_val(i);theta1_val(j)];
		cost_val(i,j) = sum((x*theta_temp - data(:,2)) .^ 2) / (2 * length(data(:,1)));
	end
end

cost_val = cost_val';
figure;
surf(theta0_val,theta1_val,cost_val);

